package com.gzu;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import java.util.logging.Logger;

public class RequestLoggingListener implements ServletRequestListener {

    private static final Logger logger = Logger.getLogger(RequestLoggingListener.class.getName());

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        // 在请求开始时，我们不进行任何操作，只是记录开始时间
        // 将开始时间存储在请求属性中，以便在请求结束时可以获取
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        request.setAttribute("startTime", System.currentTimeMillis());
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        // 在请求结束时，我们记录结束时间并计算处理时间
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        long startTime = (Long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        long processingTime = endTime - startTime;

        // 获取请求的详细信息
        String clientIP = request.getRemoteAddr();
        String requestMethod = request.getMethod();
        String requestURI = request.getRequestURI();
        String queryString = request.getQueryString();
        String userAgent = request.getHeader("User-Agent");

        // 构建日志信息
        String logMessage = String.format(
                "Request Details:\n" +
                        "Request Time: %s\n" +
                        "Client IP: %s\n" +
                        "Request Method: %s\n" +
                        "Request URI: %s\n" +
                        "Query String: %s\n" +
                        "User-Agent: %s\n" +
                        "Processing Time: %d ms",
                new java.util.Date(endTime), clientIP, requestMethod, requestURI, queryString, userAgent, processingTime);

        // 记录日志
        logger.info(logMessage);
    }
}